package com.wsx.ones.kafka;

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;

/**
 * Created by wangshuaixin on 17/6/19.
 */
public class KafkaProducer {

    public static void main(String[] args) {

        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");

        props.put("acks", "all");
        props.put("retries", 0);
        props.put("batch.size", 16384);
        props.put("linger.ms", 1);
        props.put("buffer.memory", 33554432);
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        //配置partitionner选择策略，可选配置
        //props.put("partitioner.class", "cn.ljh.kafka.kafka_helloworld.SimplePartitioner2");

        Producer<String, String> producer = new org.apache.kafka.clients.producer.KafkaProducer<String, String>(props);

        for (int i = 0; i < 100; i++) {
            ProducerRecord<String, String> record =
                    new ProducerRecord<String, String>("hello", "key" + i, "value" + i);

            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception e) {
                    if (null == e) {
                        System.out.println(metadata.offset());
                    } else {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
